// src/parsers/universalParser.ts
import type { UniversalFlowNode, UniversalFlowEdge, SourceFormat } from '@/models/universalFlow.ts';

// Remove old imports for XML base/transformer
// import { transformXmlToUniversal } from './transformers/xmlToUniversalTransformer';
// import { parseXmlToDom } from './baseParsers/xmlDomParser';

// --- IMPORT NEW XML PARSERS (Correct paths) ---
import { parse as parseWithDom } from './universal/domUniversalParser'; // <-- Use the combined DOM parser
import { parse as parseWithFastXml } from './universal/fastXmlUniversalParser';
import { parse as parseWithLibxml2 } from './universal/libxml2UniversalParser'; // <-- Corrected filename assumption
import { parse as parseWithJson } from './universal/jsonUniversalParser'; // <-- Import the new JSON parser

// --- IMPORT the new Script Parser --- 
import { parseScriptToUniversal } from './universal/scriptUniversalParser'; // SWC Parser
// REMOVE old Babel parser import
// import { parseBabelToUniversal } from './universal/babelUniversalParser'; // OLD Babel Parser
// IMPORT NEW V2 Babel parser
import { parseBabelV2ToUniversal } from './universal/babelV2UniversalParser'; // NEW V2 Babel Parser

// --- IMPORT Universal Settings Store --- (Path seems correct)
import { useUniversalVisualizerSettingsStore } from '@/stores/universalVisualizerSettingsStore'; // <-- Use the correct store name

// --- Interface for the Universal Parse Result (Keep as is) ---
export interface ParseUniversalResult {
    success: boolean;
    error?: string;
    nodes: UniversalFlowNode[];
    edges: UniversalFlowEdge[];
    rootId: string | null; // Added rootId
    rawDocument?: Document | object | any; // Keep rawDocument optional
}

/**
 * Parses content of a given format and transforms it into the Universal Flow structure.
 * This is the main entry point for the universal parsing system.
 *
 * @param content The string content to parse.
 * @param format The format of the content ('xml', 'json', etc.).
 * @returns A Promise resolving to the ParseUniversalResult (can be async if parsers/transformers are).
 */
export async function parseToUniversal(content: string, format: SourceFormat): Promise<ParseUniversalResult> {
    console.log(`[Universal Parser] Routing format: ${format}`);
    const visualizerSettings = useUniversalVisualizerSettingsStore(); // Use correct store variable

    try {
        switch (format) {
            case 'xml':
                const xmlParserType = visualizerSettings.selectedXmlParser;
                console.log(`[Universal Parser] Using XML parser: ${xmlParserType}`);

                // --- Choose parser based on settings ---
                switch (xmlParserType) {
                    case 'fast-xml':
                        return parseWithFastXml(content); // Directly call the universal parser
                    case 'libxml2':
                        return parseWithLibxml2(content); // Directly call the universal parser
                    case 'dom':
                    default:
                        return parseWithDom(content); // Directly call the universal parser
                }

            case 'json':
                // --- Call the new JSON parser ---
                return parseWithJson(content);

            // --- ADD Cases for JS/TS --- 
            case 'javascript':
            case 'typescript':
                // NEW: Check selected script parser engine
                const scriptEngine = visualizerSettings.scriptParserEngine;
                console.log(`[Universal Parser] Using script parser: ${scriptEngine}`);
                if (scriptEngine === 'babel') {
                    // REPLACE call to old parser with call to V2 parser
                    return await parseBabelV2ToUniversal(content, format);
                    // return await parseBabelToUniversal(content, format); // OLD Call
                } else { // Default to 'swc'
                    return await parseScriptToUniversal(content, format);
                }

            case 'yaml':
                // TODO: Implement YAML parsing and transformation using new base parser/transformer structure
                console.warn('YAML parsing for universal flow not yet implemented.');
                return { success: false, error: 'YAML parser not implemented', nodes: [], edges: [], rootId: null };

            case 'toml':
                // TODO: Implement TOML parsing and transformation using new base parser/transformer structure
                console.warn('TOML parsing for universal flow not yet implemented.');
                return { success: false, error: 'TOML parser not implemented', nodes: [], edges: [], rootId: null };

            case 'unknown':
            default:
                console.error(`Unsupported format for universal parsing: ${format}`);
                return { success: false, error: `Unsupported format: ${format}`, nodes: [], edges: [], rootId: null };
        }
    } catch (error: any) {
        console.error(`[Universal Parser] Failed to parse/transform format ${format}:`, error);
        return {
            success: false,
            error: `Universal Parse/Transform Error: ${error.message || 'Unknown error'}`,
            nodes: [],
            edges: [],
            rootId: null,
        };
    }
}